// pages/home/home.js
var api = require('../../../utils/api.js');
var liveroom = require('../../../utils/liveroom.js');
var config = require('../../../config.js');
// var getlogininfo = require('../../../getlogininfo.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    roomID: '',
    roomName: '',
    pureAudio: false,
    role: 'audience',
    showLiveRoom: false,
    rooms: [],
    comment: [],
    linked: false,
    debug: false,
    // inputMsg: [],
    muted: false,
    toview: '',
    
    roomid:'',
    roomID: '',         // 房间id
    roomname: '',       // 房间名称
    beauty: 5,
    muted: false,
    debug: true,
    inputMsg: '',     // input信息
    comment: [],      // 评论区信息
    frontCamera: true,



    animationData: {},
    isImShow: true,
    isMicShow: false,
    isGiftShow: false,
    btnMicValue: 1,
    btnMicText:'上麦',
    inputFocus: false,
    isIphone:false
  
  },

  // 上麦列表
  getMicList: function(e){
    let that = this;
    // 1为请求上麦列表  2为让小主播下麦
    if (e.target.dataset.btnflag==1){
      that.setData({
        isImShow: false,
        isMicShow: true,
        isGiftShow:false
      });
    }

  },

  onRoomEvent: function (e) {
    var self = this;
    var args = e.detail;
    console.log('onRoomEvent', args)
    switch (args.tag) {
      case 'roomClosed': {
        wx.showModal({
          content: `房间已解散`,
          showCancel: false,
          complete: () => {
            wx.navigateBack({ delta: 1 })
          }
        });
        break;
      }
      case 'error': {
        wx.showToast({
          title: `${args.detail}[${args.code}]`,
          icon: 'none',
          duration: 1500
        })
        break;
      }
      case 'LinkOn': { // 连麦连上
        self.setData({
          linked: true
        })
        break;
      }
      case 'LinkOut': { //连麦断开
        self.setData({
          linked: false
        })
        break;
      }
      case 'recvTextMsg': {
        console.log('收到消息:', e.detail.detail);
        var msg = e.detail.detail;
        self.data.comment.push({
          content: msg.message,
          name: msg.userName,
          time: msg.time
        });
        self.setData({
          comment: self.data.comment,
          toview: ''
        });
        // 滚动条置底
        self.setData({
          toview: 'scroll-bottom'
        });
        break;
      }
      case 'joinPusher': {
        var jioner = args.detail;
        wx.showModal({
          content: `${jioner.userName} 请求连麦`,
          success: function (sm) {
            if (sm.confirm) {
              console.log('用户点击同意')
              self.component && self.component.respondJoinReq(true, jioner);
            } else if (sm.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        break;
      }
      default: {
        console.log('onRoomEvent default: ', e)
        break;
      }
    }
  },

  start: function () {
    var self = this;
    self.component = self.selectComponent("#liveroomid");
    console.log('self.component: ', self.component);
    console.log('self:', self);
    self.component.start();
    
  },

  changeCamera: function () {
    var rtcroomCom = this.selectComponent('#rtcroom');
    if (rtcroomCom) {
      rtcroomCom.switchCamera();
    }
    this.setData({
      frontCamera: !this.data.frontCamera
    });
  },
  setBeauty: function () {
    this.data.beauty = (this.data.beauty == 0 ? 5 : 0);
    this.setData({
      beauty: this.data.beauty
    });
  },
  changeMute: function () {
    this.data.muted = !this.data.muted;
    this.setData({
      muted: this.data.muted
    });
  },
  showLog: function () {
    this.data.debug = !this.data.debug;
    this.setData({
      debug: this.data.debug
    });
  },

  bindInputMsg: function (e) {
    this.setData({
      inputMsg : e.detail.value
    })
  },


  sendComment: function () {
    var self = this;
    if (self.component) {
      self.component.sendTextMsg(self.data.inputMsg);
      this.setData({
        inputMsg: ''
      });
    }
  },



  

  // 礼物列表
  getGiftList: function(){
    var that = this;
    that.setData({
      isImShow: false,
      isMicShow: false,
      isGiftShow: true
    });

  },
  // 关闭上麦列表
  closeMicList: function () {
    this.setData({
      isImShow: true,
      isMicShow: false,
      isGiftShow: false
    });
  },
  // 关闭礼物列表
  closeGiftList: function () {
    this.setData({
      isImShow: true,
      isMicShow: false,
      isGiftShow: false
    });
  },
  focusInput: function(){
    this.setData({
      inputFocus: true
    });
  },
  blurInput: function (e) {
    let that = this;
    if (e.detail.value==''){
      that.setData({
        inputFocus: false
      });
    }
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      userbaseinfo: api.getStorageData().userbaseinfo,
    });
    var that = this;
    console.log(options);
    console.log('room.js onLoad');
    options.userName = that.data.userbaseinfo.data.nickname;
    var time = new Date();
    time = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
    console.log('*************开始多人音视频：' + time + '**************');
    this.data.role = options.type;
    this.data.roomID = options.roomID || '';
    this.data.roomname = options.roomName;
    this.data.username = options.userName;
    var role = options.type == 'presenter' ? 'presenter' : 'audience';

    if (role == 'audience') {
       api.post({
        url: 'Live/enter',
        data: {
          token: that.data.userbaseinfo.token,
          lid: options.roomID,
          status: 1
        },
        success: data => {
          if (data.code == 200) {
            console.log(data);
      
            that.setData({
              roomName: options.roomName,
              userName: options.userName,
              // pureAudio: JSON.parse(options.pureAudio),
              role: role,
              showLiveRoom: true,
              'audience.pusherName': data.data.info.name,
              'audience.pusherID': data.data.info.uid,
              'audience.accelerateUrl': data.data.play[0].url

            }, function () {
              console.log('======> page data: ', that.data);
              that.start();              
            });

            

          } else {

          }

        }
      });

    } else {
      that.setData({
        roomName: options.roomName,
        userName: options.userName,
        // pureAudio: JSON.parse(options.pureAudio),
        role: role,
        showLiveRoom: true
      }, function () {
        console.log('======> page data: ', that.data);
        that.start();
      })
    }



    wx.getSystemInfo({
      success: function (res) {

        let reg = /iPhone/;
        if (res.model.match(reg)) {
          that.setData({
            isIphone:true
          })
        }
        console.log(res);
        // 可使用窗口宽度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 计算主体部分高度,单位为px
        that.setData({
          // second部分高度 = 利用窗口可使用高度 - first部分高度（这里的高度单位为px，所有利用比例将300rpx转换为px）
          bot_scroll_height: (res.windowHeight - res.windowWidth / 750 * (500 + 42 + 70)) * 750 / res.windowWidth
        })
      }
    })



    wx.getStorage({
      key: 'livedata',
      success: function (res) {
        that.setData({
          playURL: res.data.play,
          pushURL: res.data.push,
          userbaseinfo: api.getStorageData().userbaseinfo,
          wxuserinfo: api.getStorageData().wxUserInfo
        });
        afterGetData(res.data, that.data.userbaseinfo)
      }
    });
    function afterGetData(livedata, userbaseinfo){
      liveroom.login({
        data: {
          accType: 25435,
          sdkAppID: 1400084282,
          userID: String(livedata.uid),
          roomID: livedata.channel,
          channel: livedata.channel,
          userName: userbaseinfo.data.nickname,
          userSig: userbaseinfo.tim,
          token: userbaseinfo.token,

        }
      });

    };


    // 在线人员

    // api.post()
  },

  liveStart: function(param){
    var that = this;
    that.setData({
      mid: param.mid
    });
    console.log('000000000000000')
    console.log(that);
    api.post({
      url: 'Meeting/enter',
      data: {
        token: String(that.data.storageContent.token),
        mid: param.mid,
        status:1
      },
      success: data => {
        if (data.code == 200) {
          console.log(data);
         
          data= data.data;
          // that.setData({
          //   pushURL: data.allurl[0].url
          // });

          
        } else {
         
        }

      }
    });

  },

  liveEnd: function () {
    var that = this;
    api.post({
      url: 'Meeting/end',
      data: {
        token: String(that.data.storageContent.token),
        mid: that.data.mid,
        status: 2
      },
      success: data => {
        if (data.code == 200) {
          console.log(data);
        } else {

        }

      }
    });

  },



  /**
 * 推流状态事件
 */
  onPush: function (ret) {
    var self = this;
    console.log('推流情况：', ret.detail.code);
    switch (ret.detail.code) {
      case 1002: {
        console.log('推流成功：', ret.detail.code);
        if (!self.data.isInRoom) {
          self.setData({ isInRoom: 1 });
          self.create();
        }
        break;
      };
      case -1301: {
        console.log('打开摄像头失败: ', ret.detail.code);
        wx.showModal({
          title: '提示',
          content: '打开摄像头失败，请再次尝试',
          showCancel: false,
          complete: function () {
            var pages = getCurrentPages();
            console.log(pages, pages.length, pages[pages.length - 1].__route__);
            if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/liveroom/room/room')) {
              wx.navigateBack({ delta: 1 });
            }
          }
        });
        break;
      };
      case -1302: {
        console.log('打开麦克风失败: ', ret.detail.code);
        wx.showModal({
          title: '提示',
          content: '打开麦克风失败，请再次尝试',
          showCancel: false,
          complete: function () {
            var pages = getCurrentPages();
            console.log(pages, pages.length, pages[pages.length - 1].__route__);
            if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/liveroom/room/room')) {
              wx.navigateBack({ delta: 1 });
            }
          }
        });
        break;
      };
      case -1307: {
        console.log('推流连接断开: ', ret.detail.code);
        // 推流连接断开就做退房操作
        self.exit();
        wx.showModal({
          title: '提示',
          content: '推流已断开，请检查网络状态后重试',
          showCancel: false,
          complete: function () {
            var pages = getCurrentPages();
            console.log(pages, pages.length, pages[pages.length - 1].__route__);
            if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/liveroom/room/room')) {
              wx.navigateBack({ delta: 1 });
            }
          }
        });
        break;
      };
      case 5000: {
        console.log('收到5000: ', ret.detail.code);
        // 收到5000就退房
        self.exit();
        self.data.exit = 5000;
        break;
      };
      default: {
        // console.log('推流情况：', ret.detail.code);
      }
    }
  },
  onPlay: function (ret) {
    var self = this;
    console.log('拉流情况：', ret.detail.code);
    switch (ret.detail.code) {
      case -2301: {
        // 多次拉流失败
        self.exit();
        wx.showModal({
          title: '提示',
          content: '进入房间失败',
          showCancel: false,
          complete: function () {
            var pages = getCurrentPages();
            console.log(pages, pages.length, pages[pages.length - 1].__route__);
            if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/liveroom/room/room')) {
              wx.navigateBack({ delta: 1 });
            }
          }
        });
        break;
      };
    }
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var self = this;
    wx.setNavigationBarTitle({
      title: self.data.roomName
    })
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var self = this;
    console.log('room.js onShow');
    // 保持屏幕常亮
    
    wx.setKeepScreenOn({
      keepScreenOn: true
    });

    // var animation = wx.createAnimation({
    //   duration: 1000,
    //   timingFunction: 'ease',
    // })

    // this.animation = animation

    // animation.scale(2, 2).rotate(45).left(40).step()

// var that = this;
//     setTimeout(function(){
//       animation.translate(100, 100).step({ duration: 2000 })
//       that.setData({
//         animationData: animation.export()
//       })
//     },3000)
    
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let self = this;
    if (this.data.role =='presenter'){
      api.post({
        url: 'Live/end',
        data: {
          token: String(self.data.userbaseinfo.token),
          lid: self.data.roomID
        },
        success: data => {
          if (data.code == 200) {
            console.log(data);
          } else {

          }
        }
      });
    }
    
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})